package com.gzw.scm.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.gzw.scm.DEL.DBManager;
import com.gzw.scm.MyApplication;
import com.gzw.scm.R;
import com.gzw.scm.adapter.BDAdapter;
import com.gzw.scm.base.NewBaseActivity;
import com.gzw.scm.bean.BDInfo;
import com.gzw.scm.bean.Bindinfo;
import com.gzw.scm.bean.CodeInfo;
import com.gzw.scm.bean.SCBDInfo;
import com.gzw.scm.utils.BtnUtils;
import com.gzw.scm.utils.HttpUtils;
import com.gzw.scm.utils.JsonUtil;
import com.gzw.scm.utils.T;
import com.gzw.scm.utils.UrlUtils;
import com.gzw.scm.view.SwipeRefreshLayout;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 绑定
 * Created by Administrator on 2018/5/24.
 */

public class NewBDZZXActivity extends NewBaseActivity {
    private Context mContext;
    private RecyclerView mRecyclerView;
    private Toolbar toolbar;
    private Intent intent;
    private Button btn_sure,btn_delete;
    private TextView tv_seleteAll,tv_title,tv_num;
    private boolean isCheck = false;
    private DBManager dbManager;
    private BDAdapter bdAdapter;
    private ProgressDialog mProgressDialog;
    private SwipeRefreshLayout mSwipeLayout;
    private String dataType;
    private BDInfo bdInfo;
    private List<BDInfo> ls_bdInfo,lsbh;
    private String type;
    private List<Bindinfo> ls_scbd;
    private Logger log;


    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_new_bd);
    }

    @Override
    protected void initViews() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        mRecyclerView = (RecyclerView) findViewById(R.id.rv_fp);
        btn_sure = (Button)findViewById(R.id.btn_sure);
        btn_delete = (Button)findViewById(R.id.btn_delete);
        tv_seleteAll = (TextView) findViewById(R.id.ic_head2).findViewById(R.id.tv_selectAll);
        tv_title= (TextView) findViewById(R.id.ic_num).findViewById(R.id.tv_title);
        tv_num= (TextView) findViewById(R.id.ic_num).findViewById(R.id.tv_num);
        log=Logger.getLogger(this.getClass());
    }

    @Override
    protected void initData() {
        mContext = this;
        intent = getIntent();
        type=intent.getStringExtra("type");

        if(type.equals("0")){
            toolbar.setTitle("箱码绑定");
            dataType="rdcbd";
        }else if(type.equals("1")){
            toolbar.setTitle("箱码补绑");
            dataType="rdcbb";
        }
        tv_title.setText("已扫数量:  0");
        tv_num.setText("累计数量:  0");
        setSupportActionBar(toolbar);
        dbManager=new DBManager(mContext);
        bdInfo=new BDInfo();
        ls_bdInfo=new ArrayList<>();

        /**
         * 刷新框架
         * */
        mRecyclerView.setHasFixedSize(true);
        //设置布局管理器
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        //设置Item增加、移除动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        //添加默认分割线
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);

        mSwipeLayout.setColor(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        mSwipeLayout.setMode(SwipeRefreshLayout.Mode.DISABLED);
        mSwipeLayout.setLoadNoFull(false);

//        SelectTask selectTask = new SelectTask();
//        selectTask.execute();

        SelectNum();
    }

    @Override
    protected void initEvents() {
        toolbar.setNavigationOnClickListener(new myOnClick());
        btn_sure.setOnClickListener(new myOnClick());
        btn_delete.setOnClickListener(new myOnClick());
        tv_seleteAll.setOnClickListener(new myOnClick());

        setData();
    }

    class myOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.btn_sure:
                    if(BtnUtils.isFastClick()){
                        senddata();
                    }
                    break;
                case R.id.btn_delete:
                    if(BtnUtils.isFastClick()){
                        deleteZzxbh();
                    }
                    break;
                case R.id.tv_selectAll:
                    if (ls_bdInfo != null) {
                        if (isCheck == false) {
                            // 遍历list的长度，将MyAdapter中的map值全部设为true
                            for (int i = 0; i < ls_bdInfo.size(); i++) {
                                BDAdapter.getIsSelected().put(i, true);
                            }
                            bdAdapter.notifyDataSetChanged();
                            //改变状态
                            isCheck = true;
                        } else {
                            // 遍历list的长度，将已选的按钮设为未选
                            for (int i = 0; i < ls_bdInfo.size(); i++) {
                                if (BDAdapter.getIsSelected().get(i)) {
                                    BDAdapter.getIsSelected().put(i, false);
                                }
                            }
                            bdAdapter.notifyDataSetChanged();
                            isCheck = false;
                        }
                    }
                    break;

                default:
                    finish();
                    break;
            }
        }
    }

    /**
     * 扫描结果
     * */
    @Override
    protected String scanRelust(String code){
        panduan(code);
        return code;
    }


    /**
     * 判断扫描条码类型
     * */

    private void panduan(String message){
        if(message.contains("SSID")){
            CodeInfo codeInfo = JsonUtil.getPerson(message, CodeInfo.class);
            String code = codeInfo.getNO();
            savecode("0",code);
        }else if(message.substring(0,1).equals("P")&&message.length()==11){
            savecode("1",message);
        }else{
            T.showShort(mContext,"该码不符合规则");
        }
    }


    /**
     * 保存扫描二维码和一维码
     * 0-二维码，1-一维码
     * */
    private void savecode(String type,String code){
        List<BDInfo> ls_info = dbManager.SelectBDInfo(MyApplication.getUserInfo().getDid(),dataType);
        if(ls_info.size()>0){
            if(ls_info.get(0).getXm()==null||ls_info.get(0).getZzxbh()==null){
                bdInfo = ls_info.get(0);
            }
        }
        if(type.equals("0")){
            if(dbManager.isBdCode2(code,MyApplication.getUserInfo().getDid(),dataType,"1")){
                T.showShort(mContext,"该周转箱编号已扫描");
                return;
            }
            if(bdInfo.getZzxbh()==null){
                if(bdInfo.getXm()!=null){
                    dbManager.deleteByxm(bdInfo ,MyApplication.getUserInfo().getDid(),dataType);
                }
                bdInfo.setZzxbh(code);
                dbManager.addBdinfo(bdInfo,dataType ,MyApplication.getUserInfo().getDid(),"1");
                setData();
            }else {
                T.showShort(mContext,"请扫描箱标签一维码");
            }
        }else if(type.equals("1")){

            if(dbManager.isBdCode1(code,MyApplication.getUserInfo().getDid(),dataType)){
                T.showShort(mContext,"该箱码已扫描");
                return;
            }

                if(bdInfo.getXm()==null){
                    if(bdInfo.getZzxbh()!=null){
                        dbManager.deleteByzzx(bdInfo ,MyApplication.getUserInfo().getDid(),dataType);
                    }
                    bdInfo.setXm(code);
                    dbManager.addBdinfo(bdInfo,dataType ,MyApplication.getUserInfo().getDid(),"1");
                    setData();

                }else {
                    T.showShort(mContext,"请扫描周转箱二维码");
                }
        }

        if(bdInfo.getZzxbh()!=null&&bdInfo.getXm()!=null){
            bdInfo=new BDInfo();
        }

    }

    private void setData(){
        ls_bdInfo.clear();
        ls_bdInfo =new ArrayList<>();
        List<BDInfo> ls_bd = dbManager.SelectBDInfo(MyApplication.getUserInfo().getDid(),dataType);

        Integer scanNum = 0;
        if(ls_bd.size()>0){
            if(ls_bd.get(0).getXm()==null||ls_bd.get(0).getZzxbh()==null){
                scanNum=ls_bd.size()-1;
            }else{
                scanNum=ls_bd.size();
            }

        }
        tv_title.setText("已扫数量:"+    String.valueOf(scanNum));
        if(ls_bd==null){
            return;
        }else {
            ls_bdInfo.addAll(ls_bd);
        }
        if(ls_bdInfo==null){
            return;
        }

        bdAdapter = new BDAdapter(ls_bdInfo,mContext);
        mRecyclerView.setAdapter(bdAdapter);

        bdAdapter.setOnRecyclerViewListener(new BDAdapter.OnRecyclerViewListener() {
            @Override
            public void onItemClick(int position) {
                if(BDAdapter.getIsSelected().get(position)==true){
                    BDAdapter.getIsSelected().put(position, false);
                    bdAdapter.notifyDataSetChanged();
                }else{
                    BDAdapter.getIsSelected().put(position, true);
                    bdAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public boolean onItemLongClick(int position) {
                return false;
            }
        });
    }

    /**
     * 删除周转箱编号
     * */
    private void deleteZzxbh(){
        List<BDInfo> lsbh=new ArrayList<>();
        for (int i = 0; i < ls_bdInfo.size(); i++) {
            if (bdAdapter.getIsSelected().get(i)) {
                lsbh.add(ls_bdInfo.get(i));
            }
        }
        if(lsbh.size()==0){
            T.showShort(mContext,"请先选择要删除的信息!");
        }else {
            for (BDInfo bdInfo1 : lsbh) {
                if (bdInfo1.getXm() == null && bdInfo1.getZzxbh() != null) {
                    bdInfo=new BDInfo();
                }
                if (bdInfo1.getXm() != null && bdInfo1.getZzxbh() == null) {
                    bdInfo=new BDInfo();
                }
            }
            showDeleteInfo(lsbh);
        }
    }

    /**
     * 删除数据是的提示框
     * */
    private void showDeleteInfo(final List<BDInfo> ls_bh){
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("确定要删除这"+ls_bh.size()+"个编号吗?");
        builder.setPositiveButton("确定", (dialog, which) ->  {
            dbManager.deleteBDInfo(ls_bh,MyApplication.getUserInfo().getDid(),dataType);
            setData();
        });
        builder.setNegativeButton("取消", (dialog, which) -> {
        });
        builder.show();
    }

    /**
     * 上传绑定信息
     * */
    private void senddata(){

        lsbh=new ArrayList<>();
        for (int i = 0; i < ls_bdInfo.size(); i++) {
            if (bdAdapter.getIsSelected().get(i)) {
                lsbh.add(ls_bdInfo.get(i));
            }
        }

        if(lsbh.size()==0){
            T.showShort(mContext,"请先选择绑定信息");
        }else {
            ls_scbd  = new ArrayList<>();
            for(BDInfo bdInfo:lsbh) {
                if (bdInfo.getXm() == null || bdInfo.getZzxbh() == null) {
                    T.showShort(mContext, "请完成周转箱编号和箱码的对应扫描");
                    return;
                }else{
                    Bindinfo bindinfo = new Bindinfo();
                    bindinfo.setBelongid(String.valueOf(MyApplication.getUserInfo().getBelongId()));
                    bindinfo.setDepartmentid(String.valueOf(MyApplication.getUserInfo().getDid()));
                    bindinfo.setTboxno(bdInfo.getZzxbh());
                    bindinfo.setBoxnumber(bdInfo.getXm());
                    ls_scbd.add(bindinfo);
                }
            }

            String json = JsonUtil.toJson(ls_scbd);
//            Binding(json);

            BindingTask bindingTask = new BindingTask();
            bindingTask.execute(json);
        }
    }


    /**
     * 上传的数据请求
     * 绑定
     * */
    public class BindingTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
        }

        protected String doInBackground(String... params) {
            return HttpUtils.doPost(UrlUtils.getInstance().getNewJavaUrl("Binding.do", "Binding"),"json="+params[0]);
        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();

            try {
                if (result == null || result.length() == 0) {
                    showAlertDialog("连接异常");
                    return;
                }

                if(result.contains("yc")){
                    showAlertDialog("操作失败,请重新操作或进行运维申请");
                    return;
                }
                if(result.contains("map")){
                    String map = JsonUtil.getMsg(result,"map").toString();
                    BindingInfo  bindingInfo = JsonUtil.getPerson(map,BindingInfo.class);
                    List<String> ls_tboxsState = bindingInfo.getTboxsState();
                    List<String> ls_tboxsBd = bindingInfo.getTboxsBd();
                    List<String> ls_Boxnumber = bindingInfo.getBoxnumber();
                    List<String> ls_Tbonumberbd = bindingInfo.getTbonumberbd();
                    List<String> ls_Tbonumberdid = bindingInfo.getTbonumberdid();
                    List<String> ls_succ = bindingInfo.getSucc();
                    List<String> ls_err = bindingInfo.getErr();

                    String succMsg="",errMsg="",tboxsStateMsg="",tboxsBdMsg="",
                            BoxnumberMsg="",TbonumberbdMsg="",TbonumberdidMsg="";
                    if(ls_succ.size()>0){
                        SelectNum();
                        succMsg="成功绑定周转箱"+ls_succ.size()+"个";
                        for(String bh:ls_succ){
                            dbManager.deleteByzzxbh(bh,MyApplication.getUserInfo().getDid(),dataType);
                        }
                        setData();
                    }
                    if(ls_tboxsState.size()>0){
                        String tboxsState = JsonUtil.toJson(ls_tboxsState);
                        tboxsStateMsg="周转箱"+tboxsState+"不符合绑定条件,请检查状态";
                    }
                    if(ls_tboxsBd.size()>0){
                        String tboxsBd = JsonUtil.toJson(ls_tboxsBd);
                        tboxsBdMsg="周转箱"+tboxsBd+"已绑定";
                    }
                    if(ls_Boxnumber.size()>0){
                        String Boxnumber = JsonUtil.toJson(ls_Boxnumber);
                        BoxnumberMsg ="箱标签"+Boxnumber+"不符合绑定条件,请检查状态";
                    }
                    if(ls_Tbonumberbd.size()>0){
                        String Tbonumberbd = JsonUtil.toJson(ls_Tbonumberbd);
                        TbonumberbdMsg ="箱标签"+Tbonumberbd+"已绑定";
                    }
                    if(ls_Tbonumberdid.size()>0){
                        String Tbonumberdid = JsonUtil.toJson(ls_Tbonumberdid);
                        TbonumberdidMsg ="箱标签"+Tbonumberdid+"不属于本部门";
                    }
                    if(ls_err.size()>0){
                        String err = JsonUtil.toJson(ls_err);
                        errMsg ="箱标签"+err+"绑定失败";
                    }
                    String msg = succMsg+tboxsStateMsg+tboxsBdMsg+BoxnumberMsg+
                            TbonumberbdMsg+TbonumberdidMsg+errMsg;
                    showAlertDialog(msg);
                }else {
                    showAlertDialog(result);
                }

            }catch (Exception e) {
                log.info("Bind:"+e.toString()+"/result="+result);
                e.printStackTrace();
                showAlertDialog(e.toString());
            }
        }

    }

    private void Binding(String json){
        mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
        mProgressDialog.setCancelable(false);
        btn_sure.setClickable(true);

        OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
        client.newBuilder().connectTimeout(5*60,TimeUnit.SECONDS);
        client.newBuilder().readTimeout(5*60,TimeUnit.SECONDS);
        FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
        formBody.add("json",json);//传递键值对参数
        Request request = new Request.Builder()//创建Request 对象。
                .url(UrlUtils.getInstance().getNewJavaUrl("Binding.do",
                        "Binding"))
                .post(formBody.build())//传递请求体
                .build();
        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                mProgressDialog.dismiss();
                runOnUiThread(()->{
                    showAlertDialog("连接异常");
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                mProgressDialog.dismiss();
                final String result = response.body().string();

                runOnUiThread(()->{
                    try {

                        if(result.contains("yc")){
                        showAlertDialog("操作失败,请重新操作或进行运维申请");
                        return;
                    }

                    if(result.contains("map")){
                        String map = JsonUtil.getMsg(result,"map").toString();
                        BindingInfo  bindingInfo = JsonUtil.getPerson(map,BindingInfo.class);
                        List<String> ls_tboxsState = bindingInfo.getTboxsState();
                        List<String> ls_tboxsBd = bindingInfo.getTboxsBd();
                        List<String> ls_Boxnumber = bindingInfo.getBoxnumber();
                        List<String> ls_Tbonumberbd = bindingInfo.getTbonumberbd();
                        List<String> ls_Tbonumberdid = bindingInfo.getTbonumberdid();
                        List<String> ls_succ = bindingInfo.getSucc();
                        List<String> ls_err = bindingInfo.getErr();

                        String succMsg="",errMsg="",tboxsStateMsg="",tboxsBdMsg="",
                                BoxnumberMsg="",TbonumberbdMsg="",TbonumberdidMsg="";
                        if(ls_succ.size()>0){
                            SelectNum();
                            succMsg="成功绑定周转箱"+ls_succ.size()+"个";
                            for(String bh:ls_succ){
                                dbManager.deleteByzzxbh(bh,MyApplication.getUserInfo().getDid(),dataType);
                            }
                            setData();
                        }
                        if(ls_tboxsState.size()>0){
                            String tboxsState = JsonUtil.toJson(ls_tboxsState);
                            tboxsStateMsg="周转箱"+tboxsState+"不符合绑定条件,请检查状态";
                        }
                        if(ls_tboxsBd.size()>0){
                            String tboxsBd = JsonUtil.toJson(ls_tboxsBd);
                            tboxsBdMsg="周转箱"+tboxsBd+"已绑定";
                        }
                        if(ls_Boxnumber.size()>0){
                            String Boxnumber = JsonUtil.toJson(ls_Boxnumber);
                            BoxnumberMsg ="箱标签"+Boxnumber+"不符合绑定条件,请检查状态";
                        }
                        if(ls_Tbonumberbd.size()>0){
                            String Tbonumberbd = JsonUtil.toJson(ls_Tbonumberbd);
                            TbonumberbdMsg ="箱标签"+Tbonumberbd+"已绑定";
                        }
                        if(ls_Tbonumberdid.size()>0){
                            String Tbonumberdid = JsonUtil.toJson(ls_Tbonumberdid);
                            TbonumberdidMsg ="箱标签"+Tbonumberdid+"不属于本部门";
                        }
                        if(ls_err.size()>0){
                            String err = JsonUtil.toJson(ls_err);
                            errMsg ="箱标签"+err+"绑定失败";
                        }
                        String msg = succMsg+tboxsStateMsg+tboxsBdMsg+BoxnumberMsg+
                                TbonumberbdMsg+TbonumberdidMsg+errMsg;
                        showAlertDialog(msg);
                    }else {
                        showAlertDialog(result);
                    }
                    } catch (Exception e) {
                        log.info("Binding:"+e.toString()+"/result="+result);
                        e.printStackTrace();
                        showAlertDialog(e.toString());
                    }
                });
            }
        });
    }

    /**
     * 查询已绑定数量的数据请求
     *
     * */
    private void SelectNum(){
        mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
        mProgressDialog.setCancelable(false);
        btn_sure.setClickable(true);

        OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
        FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
        formBody.add("rdcid",String.valueOf(MyApplication.getUserInfo().getDid()));//传递键值对参数
        Request request = new Request.Builder()//创建Request 对象。
                .url(UrlUtils.getInstance().getNewJavaUrl("rdcpda.do",
                        "getCount"))
                .post(formBody.build())//传递请求体
                .build();
        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                mProgressDialog.dismiss();
                runOnUiThread(()->{
                    showAlertDialog("连接异常,未查询出累计数量");
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                mProgressDialog.dismiss();
                final String result = response.body().string();

                runOnUiThread(()->{
                    try {
                    if(result.contains("count")){
                        String count = JsonUtil.getMsg(result,"count").toString();
                        tv_num.setText("累计数量:  "+count);
                    }else{
                        showAlertDialog(result);
                    }
                    } catch (Exception e) {
                        log.info("SelectNum:"+e.toString()+"/result="+result);
                        e.printStackTrace();
                        showAlertDialog(e.toString());
                    }
                });
            }
        });
    }

    /**绑定返回值*/
   public class BindingInfo{
        private List<String> tboxsState;//周转箱状态异常
        private List<String> tboxsBd;//周转箱已经绑定
        private List<String> Boxnumber;//箱标签状态异常
        private List<String> Tbonumberbd;//箱标签已经绑定
        private List<String> Tbonumberdid;//箱标签不在系统中
        private List<String> succ;//成功
        private List<String> err;//失败

        public List<String> getTboxsState() {
            return tboxsState;
        }

        public List<String> getTboxsBd() {
            return tboxsBd;
        }

        public List<String> getBoxnumber() {
            return Boxnumber;
        }

        public List<String> getTbonumberbd() {
            return Tbonumberbd;
        }

        public List<String> getTbonumberdid() {
            return Tbonumberdid;
        }

        public List<String> getSucc() {
            return succ;
        }

        public List<String> getErr() {
            return err;
        }
    }
    }
